$(function () {
    // 获得商品id
    // id在 url的search
  
    let id = location.search.split('=')[1];
  
    $.ajax({
      type: "get",
      url: "../interface/getItem.php",
      data: { id },
      dataType: "json"
    }).then(res => {
  
      let pic = JSON.parse(res.picture);
      
      let template = `
      <h2>${res.title}</h2>
      <span>|</span>
      <a href="">Redmi K50 电竞版</a>
      `;
      $('.stick-left').html(template);

      let templatea = `
      <a href="./dome05.html?id=${res.id}" id="${res.id}">加入购物车</a>
      <a href="">
          <span class="iconfont icon-xin"></span>
          喜欢</a>
      `;
      $('.shopye-right-d').html(templatea);

      let  templateb = `
           <h2>${res.title}</h2>
      `;
      $('.right-ha').html(templateb);

      let templatec =`
      <div class="swiper-slide">
                         <img src="./${pic[2].src}" alt="">
                     </div> 
                     <div class="swiper-slide">
                         <img src="./${pic[3].src}" alt="">
                     </div> 
                     <div class="swiper-slide">
                         <img src="./${pic[4].src}" alt="">
                     </div>
                     <div class="swiper-slide">
                        <img src="./${pic[5].src}" alt="">
                    </div>
                    <div class="swiper-slide">
                        <img src="./${pic[6].src}" alt="">
                    </div>
      `;
      $('.swiper-wrapper').html(templatec);

      // ---------------------
      // 事件写这
      $('#additem').on('click', function () {
        add(res.id, $('#num').val());
      });
    }).catch(xhr => {
      console.log(xhr);
    });
  });
  
  function add(id, num) {
    let product = { id, num };
  
    let shop = cookie.get('shop'); // 从cookie中获取数据
  
    if (shop) { // 判断cookie中是否有数据
      // 有数据则获得一个JSON字符串
      // 转成对象
      shop = JSON.parse(shop);
  
      // 判断当前商品的id在cookie数据中是否已经存在 如果已经存在则修改数量 不添加数据
      if (shop.some(el => el.id == id)) {
        let index = shop.findIndex(elm => elm.id == id); // 找到当前商品的索引
        let count = parseInt(shop[index].num); // 获得当前商品的数量
        count += parseInt(num);
        shop[index].num = count;
      } else { // 当前商品id在cookie数据中不存在 添加数据
        shop.push(product);
      }
  
    } else { // 没有获得cookie数据时 初始化成一个数组 然后添加数据
      shop = [];
      shop.push(product);
    }
  
    cookie.set('shop', JSON.stringify(shop));
  }